/**
 * 手动任务脚本
 * 根据员工同步状态字段“未同步”和“同步中”的数据
 * 在自动同步失败之后可以通过点击按钮进行补偿数据
 * @param {string} corpid 企业微信 corpid 或 appid
 * @param {string} corpsecret 企业微信 secret
 */
(function (corpid, corpsecret) {
  var applicationId = $.context.getCurrentApplicationId();
  // 获取表单“同步中”的实例
  var conditionMap = new Packages.java.util.HashMap();
  conditionMap.put("同步状态", "1");
  var documents = $.form.getDocumentsByCondition(
    applicationId,
    "员工客户同步状态",
    conditionMap
  );
  conditionMap.put("同步状态", "2");
  documents.addAll(
    $.form.getDocumentsByCondition(
      applicationId,
      "员工客户同步状态",
      conditionMap
    )
  );

  if (documents.size() > 0) {
    // 开始同步企业微信客户
    // 获取token
    var tokenUri = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
    var tokenParams = new Packages.java.util.HashMap();
    var tokenHeader = new Packages.java.util.HashMap();
    tokenParams.put("corpid", corpid);
    tokenParams.put("corpsecret", corpsecret);
    var acceccRes = $.httpclient.sendGet(tokenUri, tokenParams, tokenHeader);
    var accessToken = JSON.parse(acceccRes).access_token;

    function getExternalContact(document, cursor) {
      cursor = cursor || "";
      var userId = document.getElementByName("员工id").getValue();
      var formName = "企微添加客户";
      var conditions = new Packages.java.util.HashMap();
      conditions.put("员工", userId);
      // 获取当前员工客户
      var customerList = $.form.getDocumentsByCondition(
        applicationId,
        formName,
        conditions
      );
      // 客户id数组
      var customerIds = [];
      if (customerList.size() > 0) {
        for (var k = 0; k < customerList.size(); k++) {
          var id = customerList.get(k).getElementByName("客户").getValue();
          customerIds.push(String(id));
        }
      }
      // 获取企业微信客户
      var uri = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/batch/get_by_user";
      var params = new Packages.java.util.HashMap();
      var headers = new Packages.java.util.HashMap();
      var json = {
        userid: userId,
        cursor: cursor,
        limit: 100,
      };
      var genderMap = ["3", "1", "2"];
      var jsonStr = $.json.objectToJsonString(json);
      headers.put("Content-Type", "application/json;charset=UTF-8");
      params.put("access_token", accessToken);
      var response = $.httpclient.sendPost(uri, params, headers, jsonStr);
      var resData = $.json.stringToJsonObject(response);
      var nextCursor = String(resData.get("next_cursor"));
      // 循环塞数据
      var list = resData.get("external_contact_list");
      if (list.size() > 0) {
        for (var i = 0; i < list.size(); i++) {
          var item = list.get(i);
          var follow = item.get("follow_info");
          var external = item.get("external_contact");
          var timestamp = follow.get("createtime") * 1000;
          var doc = $.form.createEmptyDocument(applicationId, "企微添加客户");
          // 如果已经有这个客户，直接覆盖原来的数据
          var extId = String(external.get("external_userid"));
          if (customerIds.indexOf(extId) > -1) {
            doc = customerList.get(customerIds.indexOf(extId));
          }
          var mobileStr = "";
          for (var j = 0; j < follow.get("remark_mobiles").size(); j++) {
            mobileStr += follow.get("remark_mobiles").get(j) + ",";
          }
          doc.addElement("客户", external.get("external_userid"));
          doc.addElement("企微", external.get("unionid"));
          doc.addElement("员工", follow.get("userid"));
          doc.addElement("姓名", external.get("name"));
          doc.addElement("类型", external.get("type"));
          doc.addElement("性别", genderMap[external.get("gender")]);
          doc.addElement("职位", external.get("position"));
          doc.addElement("企业简称", external.get("corp_name"));
          doc.addElement("企业全称", external.get("corp_full_name"));
          doc.addElement("添加时间", timestamp);
          doc.addElement("备注", follow.get("remark"));
          doc.addElement("客户电话", mobileStr.slice(0, -1));
          doc.addElement("同步状态", "1");
          $.form.saveFormDocument(doc, applicationId);
        }
      }
      if (nextCursor != "" && nextCursor != "undefined") {
        getExternalContact(document, nextCursor);
      } else {
        // 同步完成，修改状态
        document.addElement("同步状态", "3");
        $.form.saveFormDocument(document, applicationId);
      }
    }

    for (var l = 0; l < documents.size(); l++) {
      var document = documents.get(l);
      getExternalContact(document);
    }
  }
})("ww36614f2eb0f9d781", "8hcHPnLQNFnosu5IcfENXKxmet73LRMY8epi-GvXXmI");
